<script setup lang="ts">
// Vue
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

// Element Plus
import { ElForm, ElFormItem, ElInput, ElButton, ElImage, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// API Client
import { getUserController } from '@/api-client'
import type { CreateCaptchaResult, UserLoginRequest, UserVO } from '@/api-client'

// Assets
import logo from '@/assets/logo.svg'

const formRef = ref<FormInstance>()
const captchaId = ref<string>('')

const loginForm = ref<UserLoginRequest>({
  username: '',
  password: '',
  captcha: '',
  captchaId: '',
})

const imgObj = ref({
  captchUrl: '',
})

const loginUserVO = reactive<UserVO>({
  id: 0,
  userName: '',
  type: 0,
  remarks: '',
  avatar: '',
})

const router = useRouter()

const getCaptch = async () => {
  console.log('Getting new captcha...')
  const { createCaptcha } = getUserController()
  const result: CreateCaptchaResult = await createCaptcha({ captchaId: captchaId.value })
  if (result.data) {
    imgObj.value.captchUrl = result.data.imgBase64
    // console.log('New captcha URL:', imgObj.value.captchUrl)
    captchaId.value = result.data.captchaId
    loginForm.value.captchaId = captchaId.value
    // console.log('New captcha ID:', captchaId.value)
  } else {
    ElMessage.error('获取验证码失败')
  }
}

const rules = reactive<FormRules<typeof loginForm.value>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度应为 3-16 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度应为 6-15 个字符', trigger: 'blur' },
  ],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})

const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      console.log('Login form submitted:', loginForm.value)
      const { userLogin } = getUserController()
      const result = await userLogin(loginForm.value)
      if (result.data) {
        const { id, userName, type, remarks, avatar } = result.data
        loginUserVO.id = id
        loginUserVO.userName = userName
        loginUserVO.type = type
        loginUserVO.remarks = remarks
        loginUserVO.avatar = avatar
        const userStore = useUserStore()
        const token = result.data.token || ''
        userStore.setUser(loginUserVO)
        userStore.saveTokenToStorage(token)
        router.push({ name: 'home' })
      } else if (result.code === 2006) {
        getCaptch()
        ElMessage.error('验证码错误')
      } else {
        getCaptch()
        ElMessage.error('登录失败,账或密码错误')
      }
    } else {
      ElMessage.error('表单验证失败')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const handleRegister = () => {
  router.push({ name: 'register' })
}

onMounted(() => {
  getCaptch()
})
</script>

<template>
  <div class="login-view">
    <div class="login-form-container">
      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
        label-width="auto"
      >
        <div class="login-header">
          <img :src="logo" alt="Logo" class="logo" />
          <h1>社区管理系统</h1>
          <p class="subtitle">Han-Community</p>
        </div>
        <el-form-item label="账号：" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入你的账户"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入你的密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码：" prop="verifyCode">
          <div class="verify-code-container">
            <el-input
              id="verifyCode"
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              class="verify-code-input"
            ></el-input>
            <el-image class="verify-code-image" :src="imgObj.captchUrl" @click="getCaptch">
            </el-image>
          </div>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button type="primary" @click="handleLogin(formRef)">登录</el-button>
          <el-button @click="resetForm(formRef)">重置</el-button>
          <el-button @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="css" scoped>
.login-view {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 100vh;
  background-image: url('https://tdesign.tencent.com/starter/vue-next/assets/assets-login-bg-white-DhCleFXy.png');
  background-size: cover;
  background-position: center;
  padding-left: 15%;
}

.login-form-container {
  width: 400px;
  padding: 40px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
}

.login-header h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 14px;
  color: #888;
}

.login-form .el-form-item:not(:last-child) {
  margin-bottom: 25px;
}

.verify-code-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.verify-code-input {
  flex-grow: 1;
}

.verify-code-image {
  width: 120px;
  height: 40px;
  margin-left: 10px;
  border-radius: 10px;
  cursor: pointer;
}

.form-buttons :deep(.el-form-item__content) {
  display: flex;
  justify-content: center;
}
</style>
